<template>
  <div class="VHomeIndex">
    <van-skeleton title :row="15" :loading="isFirst">
      <van-pull-refresh v-model="loadingx" @refresh="methods.onRefresh()">
      <van-search
        v-model="value"
        @focus="() => methods.goSearch()"
        placeholder="请输入搜索关键词"
      />

      <!-- 所有供应商 -->
      <div class="pds">
        <div class="suppliers">
          <div class="suppliersType">供应商</div>
          <van-grid square>
            <van-grid-item
              v-for="value in mainData"
              :key="value"
              :text="
                value.enterpriseName.length >= 5
                  ? value.enterpriseName.substring(0, 5) + '...'
                  : value.enterpriseName
              "
              :badge="value.goodsCount"
              :to="'shop/home/merchant/' + value.id"
            >
              <template #icon>
                <img
                  :src="value.logo"
                  width="55"
                  height="45"
                  v-if="value.logo !== null"
                />
                <div
                  style="width: 50px; height: 50px"
                  v-if="value.logo === null"
                ></div>
              </template>
            </van-grid-item>
          </van-grid>
        </div>
      </div>
      <!-- 所有供应商 -->
      <div class="my_divider"></div>

      <div class="data_title_name title-name mts">折扣专区</div>
      <!-- 所有折扣商品 -->

      <div class="discounts pdw" style="padding-bottom: 120px">
        <van-row :gutter="[10, 10]">
          <van-col span="12" v-for="item in discountList" :key="item">
            <div class="discount">
              <div class="discount-supplier">
                <van-tag type="primary">{{ item.supplier }}</van-tag>
              </div>
              <div class="img">
                <img
                  :src="item.photo"
                  class="discount-img"
                  alt=""
                  @click="methods.goDetail(item.id)"
                />
              </div>
              <div class="discount-detail">
                <p class="discount-name weight">{{ item.name }}</p>
                <div class="myflex">
                  <p class="discount-specs">{{ item.specs }}</p>
                  <p class="discount-sales">
                    <van-tag type="danger">销量:{{ item.sales }} </van-tag>
                  </p>
                </div>

                <div class="myflex">
                  <p
                    class="discount-promotePrice weight red"
                    style="font-size: 12px"
                  >
                    秒杀价: ￥{{ item.promotePrice.toFixed(2) }}
                  </p>
                  <p class="discount-inventory hui" style="font-size: 12px">
                    库存:{{ item.inventory - item.sales }}
                  </p>
                </div>
                <p
                  class="discount-price red"
                  style="font-size: 12px; text-decoration: line-through"
                >
                  ￥{{ item.price.toFixed(2) }}
                </p>

                <div class="discount-carNumber">
                  <div
                    class="myflex"
                    v-if="
                      item.carCount !== 0 && item.inventory - item.sales > 0
                    "
                  >
                    <div
                      class="iconfont icon-jian1 number"
                      @click="methods.minusGoodCar(item)"
                    ></div>
                    <div
                      class="discount-number plw prw"
                      style="font-size: 16px"
                    >
                      {{ item.carCount }}
                    </div>
                    <div
                      class="iconfont icon-jia number"
                      @click="methods.addGoodCar(item)"
                    ></div>
                  </div>

                  <div
                    v-if="
                      item.carCount === 0 && item.inventory - item.sales > 0
                    "
                  >
                    <div
                      class="iconfont icon-jia number"
                      @click="methods.addGoodCar(item)"
                    ></div>
                  </div>

                  <div v-if="item.inventory - item.sales <= 0">
                    <van-tag>已售罄</van-tag>
                  </div>
                </div>
              </div>
            </div>
          </van-col>
        </van-row>

        <van-list
  v-model:loading="loading"
  :finished="finished"
  finished-text="没有更多了"
  @load="methods.onLoad"
>
</van-list>
      </div>

      <!-- 所有折扣商品 -->

      <!-- 购物车 -->
      <div class="bottomcar">
        <div style="" class="carbox myflex">
          <div class="car myflex">
            <div
              class="iconfont icon-gouwuche"
              style="font-size: 22px; margin-left: 20px"
            >
              <van-badge
                :content="likeShop.count"
                style="position: relative; bottom: 18px"
              >
                <div class="child"></div>
              </van-badge>
            </div>
            <div style="margin-right: 1.5rem">
              合计:
              <span style="font-size: 18px; font-weight: bold"
                >￥{{ likeShop.price.toFixed(2) }}</span
              >
            </div>
          </div>

          <van-button class="car-btn" @click="methods.goBuy()">
            去结算
          </van-button>
        </div>
      </div>
      <!-- 购物车 -->


    </van-pull-refresh>
    </van-skeleton>
  </div>
</template>
<script setup>
import { getPromoteGoods } from "@/api/good";
import { getSuppliers } from "@/api/home";
import { onMounted, reactive, ref, watchEffect } from "vue";
import { useRouter } from "vue-router";
const isFirst = ref(true);
const mainData = ref(); //所有供应商
const discountList = ref(); //所有折扣商品
const value = ref(); //搜索框值
const router = useRouter();
const shopCar = ref([]); //当前页面购物车
const ids = ref([]); //购物车所有商品id
const pages = ref({
  page: 1,
  limit: 10,
  total: 0,
  key: "",
});
const loading = ref(false); //触底
const finished = ref(false); //数据到底
const count = ref(0);  //下拉
    const loadingx = ref(false);  //下拉加载消失
const likeShop = ref({
  price: 0,
  count: 0,
}); //购物车总数量和价格

const data = reactive({
  name: "这是真正的主页面",
});

const methods = {
    //下拉
    onRefresh : () => {
    pages.value.limit=10;
    pages.value.page=1;
    methods.getPromoteGoods().then(()=>{
      loadingx.value=false;
    });
    },
      //触底
      onLoad : () => {
      pages.value.limit+=10;
      methods.getPromoteGoods().then(()=>{
      loading.value=false;
    });
    

    },

  //跳转到购物车页面
  goBuy: () => {
    router.push("/shop/home/buy");
  },
  //更新页面数据
  updateData: (item) => {
    //所有缓存已有的商品的id
    const carIds = ids.value.map((d) => d.id);

    item.value.map((d, i) => {
      if (carIds.includes(d.id)) {
        const arr = ids.value.find((e) => e.id === d.id);
        d.carCount = arr.carCount;
      } else {
        d.carCount = 0;
      }
    });
  },
  //更新购物车数据
  save: (shop) => {
    const result = shop.value.find((d) => d.carCount === 0);
    if (result) {
      shop.value.map((d, i) => {
        if (d.carCount === 0) {
          shop.value.splice(i, 1);
        }
      });
    }
    //存入最新数据
    localStorage.setItem("shopCar", JSON.stringify(shop.value));

    //更新数据
    shopCar.value = JSON.parse(localStorage.getItem("shopCar"));

    likeShop.value.price = 0;
    likeShop.value.count = 0;
    shopCar.value.map((d) => {
      if (d.isPromote === 1) {
        likeShop.value.price += d.promotePrice * d.carCount;
      }

      if (d.isPromote === 0) {
        likeShop.value.price += d.price * d.carCount;
      }
      likeShop.value.count += d.carCount;
    });
  },
  //购物车新增
  addGoodCar: (item) => {
    //查看购物车是否已经存在
    const result = shopCar.value.find((d) => d.id === item.id);
    if (result) {
      //已经存在，数量+1
      shopCar.value.map((d) => {
        if (item.id === d.id) {
          d.carCount += 1;

          //更新id库中的数据
          ids.value.map((e) => {
            if (e.id === d.id) {
              e.carCount += 1;
            }
          });
        }
      });
    }

    if (!result) {
      //不存在，添加进购物车
      shopCar.value.push({ ...item, carCount: 1 });
      ids.value.push({ id: item.id, carCount: 1 });
    }

    //更新存储数据
    methods.save(shopCar);
    //更新页面数据
    methods.updateData(discountList);
  },

  //购物车减少
  minusGoodCar: (item) => {
    //查看购物车是否已经存在
    const result = shopCar.value.find((d) => d.id === item.id);
    console.log(result, "kkkkkkkkkkkkkkk");
    if (result.carCount >= 1) {
      //已经存在，数量-1
      shopCar.value.map((d) => {
        if (item.id === d.id) {
          d.carCount -= 1;

          //更新id库中的数据
          ids.value.map((e, i) => {
            if (e.id === d.id) {
              e.carCount -= 1;
            }
          });
        }
      });
    }

    //数量为0，在购物车中清除 在ids库中清除
    if (result.carCount === 0) {
      console.log("清除ids");
      shopCar.value.map((d, i) => {
        if (item.id === d.id) {
          shopCar.value.splice(i, 1);
        }
      });
      ids.value.map((d, i) => {
        if (item.id === d.id) {
          ids.value.splice(i, 1);
        }
      });
    }

    //更新存储数据
    methods.save(shopCar);
    //更新页面数据
    methods.updateData(discountList);
  },
  //去详情页面
  goDetail: (id) => {
    router.push("/shop/home/detail/" + id);
  },
  //搜索框获取焦点事件
  goSearch: (e) => {
    router.push("/shop/home/search");
  },
  /**
   * 获取所有供应商
   */
  getSuppliers: async () => {
    const res = await getSuppliers({ page: 1, limit: 999 });
    if (res.result === 0) {
      mainData.value = res.data.data;
    }
  },
  /**
   * 获取所有折扣商品
   * @returns
   */
  getPromoteGoods: async () => {
    const res = await getPromoteGoods({ page: 1, limit: pages.value.limit });
    if (res.result === 0) {
      discountList.value = res.data.data;
      methods.updateData(discountList);
      isFirst.value = false;
      pages.value.total=res.data.total;
      if(pages.value.limit>=pages.value.total){
        finished.value = true;
      }else{
        finished.value = false;
      }
    }
  },
};

onMounted(() => {
  const shopCar_history = localStorage.getItem("shopCar");
  //符合条件即为不需要初始化购物车
  if (shopCar_history !== "" && shopCar_history !== null) {
    //不需要初始化购物车，将历史购物车赋值当前页面
    //缓存中的购物车
    const cars = JSON.parse(shopCar_history);
    cars.map((d) => {
      if (d.isPromote === 1) {
        likeShop.value.price += d.promotePrice * d.carCount;
      }

      if (d.isPromote === 0) {
        likeShop.value.price += d.price * d.carCount;
      }
      likeShop.value.count += d.carCount;
    });

    //赋值给本地的购物车
    shopCar.value = cars;
    //赋值给本地的购物车id和数量
    ids.value = cars.map((d) => ({ id: d.id, carCount: d.carCount }));
  } else {
    //初始化购物车
    localStorage.setItem("shopCar", JSON.stringify([]));
  }

  methods.getSuppliers();
  //因为页面数据要响应同步购物车的数据,所以必须在获取页面数据方法中将购物车的数据更新给页面
  methods.getPromoteGoods();
});
</script>

<style scoped>
/* 购物车start */
/* 右侧去结算按钮 */
.car-btn {
  flex: 2;
  height: 100%;
  background: #f04516;
  color: #fff;
  font-weight: bold;
  font-size: 18px;
  border: none;
  border-radius: 0px 50px 50px 0px;
}

/* 购物车整个盒子 */
.carbox {
  height: 40px;
  margin: auto;
  position: relative;
  margin-bottom: 55px;
  width: 96%;
}
.bottomcar {
  position: fixed;
  width: 100%;
  bottom: 0px;
  background: #fff;
}
/* 购物车左侧 */
.car {
  flex: 8;
  height: 100%;
  display: flex;
  align-items: center;
  color: #fff;
  font-size: 12px;
  border-radius: 50px 0px 0px 50px;
  background: linear-gradient(to right, #e97f08, #ea8012);
}
/* .discount-number{
  font-size: 14px !important;
} */
/* 购物车end */

.discount-supplier {
  position: absolute;
  top: 5px;
  right: 5px;
}
.number {
  color: red;
  font-size: 18px;
}
.discount-carNumber {
  position: absolute;
  right: 5px;
  bottom: 5px;
}
/* 折扣商品名称 */
.discount-name {
  font-size: 18px;
}
/* 折扣商品规格 */
.discount-specs {
  font-size: 12px;
  color: #b2b2b2;
}

.discount-img {
  width: 100%;
  height: 9rem;
  border-radius: 6px;
  /* height: 80%; */
}

.van-col:nth-child(even) {
  padding-left: 8px;
}
.discount p {
  margin: 1px;
}
.discount {
  position: relative;
  width: 100%;

  /* margin-left:10px ; */
  border-radius: 5px;
  padding: 10px;
  padding-bottom: 18px;
  box-sizing: border-box;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
}

.title-name {
  background: rgb(255, 151, 106);
  width: 7rem;
}

.suppliersType {
  font-size: 14px;
  color: #e6a23c;
  font-weight: bold;
  margin-bottom: 0.5rem;
}
.suppliers {
  border: 1px solid #eee;
  padding: 5px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
}
.VHomeIndex {
  padding: 0px;
}
.nav-tabs {
  color: rgb(15, 15, 16);
}

.adm-tabs-tab-active {
  color: var(--adm-color-text) !important;
}

.adm-tabs {
  --active-line-color: var(--adm-color-danger) !important;
  --fixed-active-line-width: 45px;
  --active-line-height: 4px;
  --active-line-border-radius: 10px;
}

.head-nav {
  height: 136px;
  border: 1px solid #eee;
  margin: 2px;
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
}

.todayData {
  /* box-sizing: border-box; */
  padding: 5px;
  margin-top: 5px;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 74px;
  /* border: 1px solid #000; */
  border-radius: 5px;
}

.todayData > div {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 18px;
  color: #fff;
}

.todayData > :nth-child(1) {
  height: 100%;
  background: #529b2e;
  border-radius: 5px 0px 0px 5px;
}

.todayData > :nth-child(2) {
  height: 100%;
  background: #e6a23c;
  border-radius: 0px 5px 5px 0px;
}

.shopList {
  /* position: relative; */
  margin-top: 5px;
  justify-content: space-between;
  display: flex;
  /* background: rgb(244, 244, 244); */
}

.shop-item {
  width: 49%;
  background: #fff;
  /* border-radius: 20px; */
  /* border: 1px solid #000; */
}

.shop-item > .shop > .shop-img {
  border-radius: 5px 5px 0px 0px;
  width: 100%;
  /* height: 100px; */
  height: 150px;
  padding-bottom: 5px;
  border-bottom: 1px solid #eee;
}

.shop-item > .shop p {
  margin: 3px;
}

.shop-item > .shop .shop-name {
  font-size: 14px;
  font-weight: bold;
}

.shop-item > .shop .shop-explain {
  color: #c2bcbc;
  font-size: 12px;
}

.shop-weight {
  color: #b2b2b2;
  font-size: 10px;
}

.shop-detail {
  padding: 0px 3px 0px 3px;
  position: relative;
}

.shop-price {
  margin-top: 5px;
  margin-bottom: 5px;
  padding-bottom: 8px;
  color: red;
}

.shop-price :nth-child(1) {
  font-size: 10px;
}

.shop-price :nth-child(2) {
  font-size: 14px;
  font-weight: bold;
}

.shop-btn {
  position: absolute;
  bottom: 6px;
  right: 3px;
}

/* .icon-gou{
   border: 1px solid #000;
   
  } */

.iconsize {
  font-size: 24px !important;
  color: red;
}

.shopNum {
  font-size: 18px;
  padding: 0px 3px 0px 3px;
  position: relative;
  bottom: 3px;
}

.shop {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.12), 0 0 6px rgba(0, 0, 0, 0.04);
  border-radius: 5px;
}

.deposits {
  margin-top: 5px;
  margin-left: 3px;
}

.inventory {
  color: #c2bcbc;
  float: right;
  position: relative;
  bottom: 2px;
}

.shop-status {
  display: flex;
  justify-content: space-between;
  padding-bottom: 2px;
  border-bottom: 1px solid #eee;
  padding: 0px 5px 5px 5px;
}

.shop-status > div {
  margin-top: 10px;
}
</style>